<?php
declare(strict_types=1);

namespace Dreamcat\ConfigClient\Impl\Saver;

use Dreamcat\ConfigClient\ConfigSaverInterface;
use Dreamcat\ConfigClient\Popo\ConfigResult;

/**
 * -
 * @author vijay
 */
class SingleSaver implements ConfigSaverInterface
{
    private $configFile;
    private $configs = [];

    /**
     * ConfigSaver constructor.
     * @param string $configFile 配置文件路径
     */
    public function __construct(string $configFile)
    {
        $this->configFile = $configFile;
    }

    /**
     * @inheritDoc
     */
    public function saveConfig(ConfigResult $configResult): bool
    {
        $this->configs[json_encode($configResult->getAppInfo())] = $configResult->getConfigurations();
        return true;
    }

    /**
     * @inheritDoc
     */
    public function onSaveAll(): void
    {
        $configs = [];
        foreach ($this->configs as $config) {
            $configs = array_merge($configs, $config);
        }
        $configStr = var_export($configs, true);
        file_put_contents($this->configFile, "<?php\nreturn {$configStr};\n");
    }
}

# end of file
